const initState = {
  cartList: [],
  storeName: '',
  totalPrice: '0.00',
  cartFlag: false
}

export default (state = initState, action) => {
  if (action.type === 'mutationInitCartList') {
    return Object.assign({}, state, {
      totalPrice: action.totalPrice,
      cartFlag: action.cartFlag,
      cartList: action.cartList
    })
  }

  if (action.type === 'mutationAdd') {
    let arr = JSON.parse(JSON.stringify(state.cartList))

    let index = arr.findIndex(item => {
      return item.goods_id === action.goodsInfo.goods_id
    })

    arr[index] = action.goodsInfo
    
    let price = state.totalPrice
    let changePrice = parseFloat(action.goodsInfo.goods_price)
    
    if (action.btnType === 'add') {
      price = (parseFloat(price) + changePrice).toFixed(2)
    } else {
      price = (parseFloat(price) - changePrice).toFixed(2)
    }

    return Object.assign({}, state, {
      cartList: arr,
      totalPrice: price
    })
  }

  if (action.type === 'mutationChangePrice') {
    return Object.assign({}, state, {
      totalPrice: action.newTotalPrice
    })
  }

  if (action.type === 'mutationAddGoods') {
    return Object.assign({}, state, {
      storeName: action.storeName
    })
  }

  return state
} 
